<?php
namespace plugin\laoha\app\controller;

use plugin\laoha\app\model\Attach;
use support\exception\BusinessException;
use support\Request;
use support\Response;
use Exception;
use Intervention\Image\ImageManagerStatic as Image;
use Throwable;

/**
 * 附件管理 
 */
class AttachController extends Crud
{
    protected $noNeedLogin = [];
    protected $dataLimit = 'personal';
    protected $dataLimitField = 'user_id';

    public function __construct()
    {
        $this->model = new Attach;
        $this->rules = $this->getRules();
    }


    /**
     * 浏览
     * @throws Throwable
     */
    public function index(Request $request)
    {
        $params = [
            'url'=>request()->fullUrl(),
            'title'=>'上传图片',
            'bread' => ['用户|/app/laoha/user/index', '图片列表'],
            'user_id'=>0,
            'data'=>[]
        ];          
        $user_id = request()->get('user_id',0) ?: user_id();
        if($user_id){  
            $this->set =  ['page_type' => 1, 'order_by' => '-id', 'per_page'=>16, 'with' => ''];         
            $this->builder = $this->model->where('user_id',$user_id)->where('type','image');
            $params['data'] = $this->list($request);  
            $params['user_id']=$user_id;          
        }      
        return $this->out($params, 'attach/index');
    }


    /**
     * 浏览附件
     * @return Response
     * @throws Throwable
     */
    public function attachment(): Response
    {
        return raw_view('attach/attachment');
    }



    /**
     * 上传文件
     */
    public function file(Request $request)
    {
        $file = current($request->file());
        if (!$file || !$file->isValid()) {
            throw new BusinessException('未找到上传文件', 400);
        }
        $img_exts = [
            'jpg',
            'jpeg',
            'png',
            'gif'
        ];
        if (in_array($file->getUploadExtension(), $img_exts)) {
            return $this->image($request);
        }

        $data = $this->up($file, 'file');
        return json_ok($data);
    }

    /**
     * 上传图片
     */
    public function image(Request $request)
    {
        $file = current($request->file());
        if (!$file || !$file->isValid()) {
            throw new BusinessException('未找到上传文件', 400);
        }
        $data = $this->up($file, 'image');
        return json_ok($data);
    }



    /**
     * 获取上传数据
     */
    protected function up($file, $uptype = 'file')
    {
        $user_id = user_id();
        if (!$file || !$file->isValid()) {
            throw new BusinessException('未找到文件', 401);
        }
        if (strpos($file->getUploadMimeType(), 'image') === 0) {
            $type = 'image';
        } elseif (strpos($file->getUploadMimeType(), 'video') === 0) {
            $type = 'video';
        } elseif (strpos($file->getUploadMimeType(), 'audio') === 0) {
            $type = 'audio';
        } else {
            $type = 'file';
        }
		if($uptype == 'image' && $type !== 'image'){
			throw new BusinessException('上传图片格式错误', 400);
		}
        $file_size = $file->getSize();
        $file_name = $file->getUploadName();

        if ($rs = $this->model->where('name', $file_name)->where('file_size', $file_size)->where('user_id', $user_id)->first()) {
            return ['url' => $rs->url, 'name' => $rs->name, 'size' => $rs->size];
        }

        $base_dir = base_path() . '/plugin/laoha/public/';
        $relative_dir = '/upload/' . $type . '/' . date('Ymd');

        $ext = strtolower($file->getUploadExtension());
        $ext_forbidden_map = ['php', 'php3', 'php5', 'css', 'js', 'html', 'htm', 'asp', 'jsp', 'exe', 'com', 'bat'];
        if (in_array($ext, $ext_forbidden_map)) {
            throw new BusinessException('不支持该格式的文件上传', 400);
        }
        $mime_type = $file->getUploadMimeType();
        $full_dir = $base_dir . $relative_dir;

        if (!is_dir($full_dir)) {
            mkdir($full_dir, 0777, true);
        }
        $relative_path = $relative_dir . '/' . bin2hex(pack('Nn', time(), random_int(1, 65535))) . ".$ext";
        $full_path = $base_dir . $relative_path;
        $url = '/app/laoha' . $relative_path;
        $file->move($full_path);

        $image_width = $image_height = 0;
        $type = 'file';
        if ($img_info = getimagesize($full_path)) {
            [$image_width, $image_height] = $img_info;
            $mime_type = $img_info['mime'];
            $type = 'image';
        }

        if (strpos($mime_type, 'video') === 0) $type = 'video';
        if (strpos($mime_type, 'audio') === 0) $type = 'audio';

        $this->model->user_id = $user_id;
        $this->model->url = $url;
        $this->model->name = $file_name;
        $this->model->file_size  = $file_size;
        $this->model->mime_type = $mime_type;
        $this->model->image_width = $image_width;
        $this->model->image_height = $image_height;
        $this->model->ext = $ext;
        $this->model->type = $type;
        $this->model->save();

        return ['url' => $url, 'name' => $file_name, 'size' => $file_size];
    }
}
